import { computed, defineComponent, h } from 'vue';
import { usePermissionsStore } from '@/stores/modules';
import { ConfigProvider, Layout, Menu, Space } from 'ant-design-vue';
import type { ItemType } from 'ant-design-vue';
import { storeToRefs } from 'pinia';
import { RouteRecordRaw, RouterLink, useRoute } from 'vue-router';
import SvgIcon from '@/components/SvgIcons/Index.vue';

const { Sider } = Layout;

const formatSubmenu = (subMenus: RouteRecordRaw[]): ItemType[] => {
  return subMenus.reduce<ItemType[]>((prev, menu) => {
    if (menu.meta?.hide) {
      return prev;
    }
    const data: ItemType = {
      key: menu.path as string,
      label: h(
        RouterLink,
        { to: menu.path },
        {
          default: () => {
            return (
              <Space>
                {menu.meta?.icon && (
                  <SvgIcon
                    name={menu.meta.icon}
                    class='w-5 h-5 mr-1'
                    strokeColor='undefined'
                  />
                )}
                {menu.meta?.title}
              </Space>
            );
          },
        },
      ),
      title: menu.meta!.title as string,
    };

    if (menu.children?.length) {
      // @ts-ignore
      data.children = formatSubmenu(menu.children);
    }
    prev.push(data);

    return prev;
  }, []);
};

export default defineComponent({
  setup() {
    const route = useRoute();
    const permissionSore = usePermissionsStore();
    const { menus } = storeToRefs(permissionSore);
    const items = computed<ItemType[]>(() => {
      return formatSubmenu(menus.value);
    });

    const selectedKeys = computed(() => [route.path]);
    const openKeys = computed(() => {
      const lastSlashIndex = route.path.lastIndexOf('/');
      const extractedPath = route.path.substring(0, lastSlashIndex);
      const paths: any = [];
      let currentPath = '';
      const parts = extractedPath.split('/').filter(Boolean);
      parts.forEach((part) => {
        currentPath += `/${part}`;
        paths.push(currentPath);
      });
      return paths;
    });
    return () => (
      <Sider width={items.value.length === 0 ? 0 : '266px'}>
        <router-link class='sidebar-logo' to={'dashboard'}>
          终端管理
        </router-link>
        <Menu
          mode='inline'
          inlineIndent={10}
          items={items.value}
          selectedKeys={selectedKeys.value}
          openKeys={openKeys.value}
          forceSubMenuRender
          class='pro-menu'
        />
      </Sider>
    );
  },
});
